import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:get/get.dart';
import 'package:oi_ai_tool/common/IconFontIcons.dart';
import 'package:oi_ai_tool/controller/home_page_controller.dart';
import 'package:oi_ai_tool/model/chat_message.dart';
import 'package:oi_ai_tool/util/oi_logger.dart';
import 'package:oi_ai_tool/widgets/oi_chat_badge.dart';
import 'package:oi_ai_tool/widgets/oi_list_view.dart';

class HomeBody extends StatefulWidget {
  const HomeBody({super.key});

  @override
  State<HomeBody> createState() => _HomeBody();
}

class _HomeBody extends State<HomeBody> {
  final HomePageController controller = Get.find<HomePageController>();
  @override
  initState() {
    super.initState();
    controller.ontextFocus();
    OiLogger.info(msg: "init");
  }

  @override
  void didUpdateWidget(covariant HomeBody oldWidget) {
    OiLogger.info(msg: "didUpdateWidget");
    super.didUpdateWidget(oldWidget);
  }

  @override
  void activate() {
    OiLogger.info(msg: "body update active");
    super.activate();
  }

  @override
  dispose() {
    super.dispose();
  }

  defaultAvator(IconData icon) {
    return Icon(
      icon,
      color: Colors.white,
      size: 20.dm,
      weight: 600,
    );
  }

  botChat(ChatMessage item, {int? itemIndex}) {
    return Container(
        margin: EdgeInsets.all(10.dm),
        // width: 393.w,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          verticalDirection: VerticalDirection.up,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            SizedBox(
              width: 30.w,
              height: 30.h,
              child: CircleAvatar(
                  child: defaultAvator(
                    IconFontIcons.iconRobot,
                  ),
                  backgroundColor: Colors.cyan),
            ),
            OiChatBadge(
              onTap: () => controller.reSendQuestion(itemIndex),
              badgeContent: Icon(
                Icons.refresh,
                color: Colors.white,
                size: 14.sp,
              ),
              child: Container(
                constraints: BoxConstraints.loose(Size.fromWidth(320.sp)),
                padding: EdgeInsets.all(12.sp),
                margin: EdgeInsets.only(left: 10.sp),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(10.r)),
                    color: Colors.white),
                child: MarkdownBody(
                  data: item.content,
                ),
              ),
            ),
          ],
        ));
  }

  userChat(ChatMessage item) {
    return Container(
      margin: EdgeInsets.all(10.dm),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        verticalDirection: VerticalDirection.up,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Container(
            constraints: BoxConstraints.loose(Size.fromWidth(320.sp)),
            margin: EdgeInsets.only(right: 10.sp),
            padding: EdgeInsets.all(10.sp),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(10.r)),
                color: Colors.white),
            child: Text(
              item.content,
              maxLines: 20,
              textAlign: TextAlign.left,
              softWrap: true,
            ),
          ),
          SizedBox(
              width: 30.w,
              height: 30.h,
              child: CircleAvatar(
                  child: defaultAvator(IconFontIcons.iconUser),
                  backgroundColor: Colors.orange)),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomePageController>(builder: (controller) {
      return Scaffold(
          // extendBody: false,
          // extendBodyBehindAppBar: false,
          resizeToAvoidBottomInset: true,
          body: SizedBox(
            height: controller.mainHeight,
            width: ScreenUtil().screenWidth,
            child: Column(children: [
              Expanded(
                flex: 1,
                child: Container(
                  margin: EdgeInsets.only(bottom: 10.h),
                  child: listBuild(),
                ),
              ),
            ]),
          ),
          bottomNavigationBar: BottomAppBar(
            height: 55.h,
            child: Row(
              children: [
                optionButtonGroup(),
                Expanded(
                  flex: 1,
                  child: Container(
                      padding: EdgeInsets.all(10.sp),
                      child: TextField(
                        enabled: controller.inputEnable,
                        readOnly: !controller.inputEnable,
                        scrollPadding: EdgeInsets.zero,
                        // autofocus: true,
                        focusNode: controller.oifocusNode,
                        controller: controller.userTalkTextController,
                        onSubmitted: (string) => controller.onSubmit(),
                        decoration:
                            InputDecoration(suffixIcon: sendButton(controller)),
                      )),
                ),
              ],
            ),
          ));
    });
  }

  Row optionButtonGroup() {
    return Row(
      children: [
        CupertinoButton(
            padding: EdgeInsets.zero,
            child: const Icon(Icons.camera_alt),
            onPressed: () {}),
        CupertinoButton(
            padding: EdgeInsets.zero,
            child: const Icon(Icons.image_outlined),
            onPressed: () {}),
        CupertinoButton(
            padding: EdgeInsets.zero,
            child: const Icon(Icons.file_upload),
            onPressed: () {}),
      ],
    );
  }

  CupertinoButton sendButton(HomePageController controller) {
    final spinkit = SpinKitCircle(
      color: Colors.cyan.shade300,
      size: 20.sp,
    );
    return controller.inputEnable
        ? CupertinoButton(
            padding: EdgeInsets.zero,
            onPressed: () => controller.onSubmit(),
            child: const Align(
              widthFactor: 0.1,
              alignment: Alignment.center,
              child: Icon(Icons.send),
            ),
          )
        : CupertinoButton(
            padding: EdgeInsets.zero,
            onPressed: () {},
            child: Align(
              widthFactor: 0.1,
              alignment: Alignment.center,
              child: spinkit,
            ),
          );
  }

  /// 构建列表
  listBuild() {
    return OiListView(
      shrinkWrap: true,
      data: controller.mockdata,
      scrollController: controller.scrollController,
      itemBuilder: (buildercontext, index) {
        ChatMessage item = controller.mockdata[index];
        bool isUser = item.role.compareTo("user") == 0;
        return chatWidget(isUser, item, index);
      },
    );
  }

  /// 用户聊天界面
  chatWidget(bool isUser, ChatMessage item, int index) =>
      isUser ? userChat(item) : botChat(item, itemIndex: index);
}
